package com.hushao.lims.weblims.service.impl;

import com.hushao.lims.weblims.domain.DepartmentInfo;
import com.hushao.lims.weblims.domain.TeacherInfo;
import com.hushao.lims.weblims.repository.DepartmentRepository;
import com.hushao.lims.weblims.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 930588706
 * @date 18/2/3
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    public Page<DepartmentInfo> listDepartmentByName(String departmentName, Pageable pageable) {
        departmentName="%"+departmentName+"%";
        return departmentRepository.findByDepartmentNameLike(departmentName,pageable);
    }

    @Override
    public DepartmentInfo getById(Integer departmentId) {
        return departmentRepository.getOne(departmentId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void remove(Integer departmentId) throws Exception {
        departmentRepository.deleteById(departmentId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveOrUpdate(DepartmentInfo department, String teacherNumber) throws Exception {

        TeacherInfo teacher= (TeacherInfo) userDetailsService.loadUserByUsername(teacherNumber);
        String message;
        if(department.getDepartmentId()==null){
            department.setTeacherInfo(teacher);
            departmentRepository.save(department);
            message="添加院部成功！";

        }else {
            DepartmentInfo departmentNew=this.getById(department.getDepartmentId());
            departmentNew.setTeacherInfo(teacher);
            departmentNew.setDepartmentName(department.getDepartmentName());
            departmentNew.setDepartmentIntro(department.getDepartmentIntro());
            departmentNew.setDepartmentTel(department.getDepartmentTel());
            departmentRepository.save(departmentNew);
            message="修改院部成功！";
        }
        return message;
    }


    @Override
    public DepartmentInfo getByName(String departmentName) {
        return departmentRepository.findByDepartmentName(departmentName);
    }
}
